package com.qfedu.mbti.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qfedu.mbti.config.RedisKeyConfig;
import com.qfedu.mbti.dao.MbtiQuestionDao;
import com.qfedu.mbti.entity.MbtiQuestion;
import com.qfedu.mbti.param.QuestionAnswer;
import com.qfedu.mbti.service.MbtiQuestionService;
import com.qfedu.mbti.vo.R;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * mbti测试题表(MbtiQuestion)表服务实现类
 *
 * @author makejava
 * @since 2024-11-04 11:43:41
 */
@Service("mbtiQuestionService")
@RequiredArgsConstructor
public class MbtiQuestionServiceImpl implements MbtiQuestionService {
    private final MbtiQuestionDao dao;
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public R queryByMeid(Integer id) {

        LambdaQueryWrapper<MbtiQuestion> wrapper=new LambdaQueryWrapper<>();
        if(id>0) {
            wrapper.eq(MbtiQuestion::getMeid, id);
        }
        wrapper.orderByAsc(MbtiQuestion::getId);

        return R.ok(dao.selectList(wrapper));
    }

    @Override
    public R answerQuestion(QuestionAnswer answer) {
        //1.查询问题
        MbtiQuestion question=dao.selectById(answer.getId());
        if(question!=null && question.getAnswer()==null){
            //没有回答过的，才可以回答
            if ("a".equals(answer.getAnswer().toLowerCase())){
                question.setAnswer(question.getAnswera());
            } else if ("b".equals(answer.getAnswer().toLowerCase())) {
                question.setAnswer(question.getAnswerb());
            }else {
                return R.fail("亲，请选择对应的选项！");
            }
            MbtiQuestion q=new MbtiQuestion();
            q.setId(question.getId());
            q.setAnswer(question.getAnswer());
            q.setUpdateTime(new Date());
            dao.updateById(q);
            return R.ok(null);
        }
        return R.fail("亲，回答问题失败！");
    }

    @Override
    public R queryByUid(String token) {
        String uid=stringRedisTemplate.opsForValue().get(RedisKeyConfig.USER_TOKEN+token);

        return R.ok(dao.selectByUid(Integer.parseInt(uid)));
    }


}

